package com.zsy._21生产者与消费者问题;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程通信：生产者与消费者问题
 * 使用 Lock 实现生产者消费者问题
 *
 * @author: zhangshuaiyin
 * @date: 2021/8/27 20:48
 */
public class LockDemo {
    public static void main(String[] args) {
        Data2 number = new Data2();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.increment();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.decrement();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.increment();
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.decrement();
            }
        }, "D").start();
    }
}

class Data2 {
    private int number = 0;

    final Lock lock = new ReentrantLock();

    final Condition condition = lock.newCondition();

    public void increment() {
        try {
            lock.lock();
            while (number != 0) {
                // 等待, 同步方法锁的是当前实例对象
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number += 1;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        try {
            lock.lock();
            while (number != 1) {
                // 等待, 同步方法锁的是当前实例对象
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number -= 1;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
